<template>
  <router-view v-if="Layout" v-slot="{ Component, route: curRoute }">
    <component :is="Layout">
      <KeepAlive :include="keepAliveNames">
        <component
          :is="Component"
          v-if="!tabStore.reloading"
          :key="curRoute.fullPath"
        />
      </KeepAlive>
    </component>
  </router-view>
</template>

<script setup>
import { useAppStore, useTabStore } from '@/store'

const layouts = new Map()
const route = useRoute()
const appStore = useAppStore()
if (appStore.layout === 'default') appStore.setLayout('')
function getLayout(name) {
  // 利用map将加载过的layout缓存起来，防止重新加载layout导致页面闪烁
  if (layouts.get(name)) return layouts.get(name)
  const layout = markRaw(
    defineAsyncComponent(() => import(`@/layouts/${name}/index.vue`))
  )
  layouts.set(name, layout)
  return layout
}
const Layout = computed(() => {
  if (!route?.matched?.length) return null
  return getLayout(route.meta?.layout || appStore.layout)
})

// 设置css变量主题色
function setupCssVar() {
  const common = appStore.naiveThemeOverrides?.common || {}
  for (const key in common) {
    useCssVar(`--${kebabCase(key)}`, document.documentElement).value =
      common[key] || ''
    if (key === 'primaryColor')
      window.localStorage.setItem('__THEME_COLOR__', common[key] || '')
  }
}
setupCssVar()

// 计算 keep-alive 白名单
const tabStore = useTabStore()
const keepAliveNames = computed(() => {
  return tabStore.tabs.filter((item) => item.keepAlive).map((item) => item.name)
})
</script>

<style lang="scss" scoped></style>
